package com.lantosec.hmrp.modules.category.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.kit.tree.TreeNodeVo;
import com.lantosec.hmrp.modules.category.entity.AssetsCategory;
import com.lantosec.hmrp.modules.category.mapper.AssetsCategoryMapper;
import com.lantosec.hmrp.modules.category.service.IAssetsCategoryService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 资产类别表 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-03-31
 */
@Service
@Primary
@Log4j2
public class AssetsCategoryServiceImpl extends ServiceImpl<AssetsCategoryMapper, AssetsCategory> implements IAssetsCategoryService {
    @Override
    public List<TreeNodeVo> getTree() {
        return categoryTree(null);
    }

    private List<TreeNodeVo> categoryTree(String id) {
        List<TreeNodeVo> list = categoryNodes(id);
        List tree = new ArrayList<TreeNodeVo>();
        if (list != null && list.size() > 0) {
            list.forEach(node -> {
                if (!node.isLeaf()) {
                    List<TreeNodeVo> children = categoryTree(node.getKey());
                    node.setChildren(children);
                }
                tree.add(node);
            });
        }
        return tree;
    }

    private List<TreeNodeVo> categoryNodes(String id) {
        List<AssetsCategory> list = getCategoryId(id);
        if (list != null && list.size() > 0) {
            List<TreeNodeVo> nodes = new ArrayList<TreeNodeVo>();
            list.forEach(result -> {
                Integer serviceLife = result.getServiceLife();
                nodes.add(new TreeNodeVo(result.getCategoryId(), result.getCategoryName(),null != serviceLife?serviceLife:null));
            });
            return nodes;
        }
        return new ArrayList<TreeNodeVo>();
    }

    private List<AssetsCategory> getCategoryId(String id) {
        return baseMapper.getCategoryId(id);
    }

    @Override
    public void create(AssetsCategory entity) {
        String parentId = entity.getParentId();
        String categoryId = null;
        if(StringUtils.isNotEmpty(parentId)){
            categoryId = baseMapper.queryMaxCategoryIdByParentId(parentId);
            entity.setCategoryId(StringUtils.isEmpty(categoryId)? parentId + "001" : categoryId);
        }else{
            categoryId = baseMapper.queryMaxCategoryId();
            entity.setCategoryId(StringUtils.isEmpty(categoryId)? "001" : categoryId);
        }
        baseMapper.insert(entity);
    }
}
